/*******************************************************************************
*  Project      : Minigate Golfin                                 
*  Program ID   : my_score.js                            
*  Description  : 스코어 관리
*
********************************************************************************
*  Program History                                                            
*  Date        Author    Description                                          
*  ----------  --------  -------------------------------------------------------- 
*  2012-06-28  김효순    Created.  
*******************************************************************************/

jQuery(function($){
	// 나의 스코어
	function clsMyScore()
	{
		this._HTMLDom = null;
		this.infoData = null;
	}
	
	clsMyScore.prototype = {
		setInfo: function(val){
			this.infoData = val;
			this.display();
		}
		, display: function(){
			var $layer = this._HTMLDom["$layer"];
			
			$layer.find("em:last").html(document.objUtil.nvl(this.infoData["스코어"], 0));
		}
	}
	
	// 평균스코어
	function clsAvgScore()
	{
		this.ssuper = null;
		
		this._init();
	}
	
	clsAvgScore.prototype = new clsMyScore();
	clsAvgScore.prototype._init = function(){
		var $layer = $("div#container div.my_h_score>dl:eq(0)");
		this._HTMLDom = {
			"$layer": $layer
		}
		this.ssuper = clsMyScore.prototype;
		
		this.setInfo({
			"스코어": 0
		});
	}
	
	// 베스트 스코어
	function clsBestScore()
	{
		this.ssuper = null;
		
		this._init();
	}
	
	clsBestScore.prototype = new clsMyScore();
	clsBestScore.prototype._init = function(){
		var $layer = $("div#container div.my_h_score>dl:eq(1)");
		this._HTMLDom = {
			"$layer": $layer
		}
		this.ssuper = clsMyScore.prototype;
		
		this.setInfo({
			"스코어": 0
		});
	}
	clsBestScore.prototype.display =function(){
		var $layer = this._HTMLDom["$layer"];
		this.ssuper.display.apply(this, arguments);
		
		$layer.find("li:eq(0)>strong").html(document.objUtil.nvl(this.infoData["골프장명"]));
		$layer.find("li:eq(1)").html(document.objUtil.nvl(this.infoData["코스명"]));
	}
	
	// 최대타수
	function clsWorstScore()
	{
		this.ssuper = null;
		
		this._init();
	}
	
	clsWorstScore.prototype = new clsMyScore();
	clsWorstScore.prototype._init = function(){
		var $layer = $("div#container div.my_h_score>dl:eq(2)");
		this._HTMLDom = {
			"$layer": $layer
		}
		this.ssuper = clsMyScore.prototype;
		
		this.setInfo({
			"스코어": 0
		});
	}
	clsWorstScore.prototype.display = clsBestScore.prototype.display;
	
	
	// 스코어통계
	function clsScoreStatList()
	{
		this._HTMLDom = null;
		this.listData = null;
		this.roundCount = null;
		
		this._init();
	}
	
	clsScoreStatList.prototype = {
		_init: function(){
			var $layer = $("div#container>div.my_stats>article.my_stats_list");
			this._HTMLDom = {
				"$layer": $layer
			}
			
			this.setList([]);
			this.setRoundCount(0);
		}
		, $getLayer: function(){
			return this._HTMLDom["$layer"];
		}
		, setList: function(thisData){
			this.listData = thisData;
			this.display();
		}
		, setRoundCount: function(val){
			this.roundCount = val;
			this.$getLayer().prev().find("strong.point_r").html("(" + this.roundCount + "회)");
		}
		, display: function(){
			var $layer = this._HTMLDom["$layer"];
			var thisClass = this;
			
			$layer.find("tbody>tr").each(function(n){
				var d = thisClass.listData[n];
				var par = n+3;
				
				d = d || {};
				
				d["더블보기"] = _util.nvl(d["더블보기"], 0);
				d["보기"] = _util.nvl(d["보기"], 0);
				d["파"] = _util.nvl(d["파"], 0);
				d["버디"] = _util.nvl(d["버디"], 0);
				d["이글"] = _util.nvl(d["이글"], 0);
				d["홀인원"] = _util.nvl(d["홀인원"], 0);
				
				var total = d["더블보기"]*(par+2) + d["보기"]*(par+1) + d["파"]*par + d["버디"]*(par-1) + d["이글"]*(par-1) + d["홀인원"];
				var per = d["더블보기"] + d["보기"] + d["파"] + d["버디"]+ d["이글"] + d["홀인원"];
				
				per = per || 1;
				
				$(this).find("td:eq(0)").html(d["더블보기"]);
				$(this).find("td:eq(1)").html(_util.roundEx((d["더블보기"]*100/per), -1) + "%");
				$(this).find("td:eq(2)").html(d["보기"]);
				$(this).find("td:eq(3)").html(_util.roundEx((d["보기"]*100/per), -1) + "%");
				$(this).find("td:eq(4)").html(d["파"]);
				$(this).find("td:eq(5)").html(_util.roundEx((d["파"]*100/per), -1) + "%");
				$(this).find("td:eq(6)").html(d["버디"]);
				$(this).find("td:eq(7)").html(_util.roundEx((d["버디"]*100/per), -1) + "%");
				
				if(n > 0){
					$(this).find("td:eq(8)").html(d["이글"]);
					$(this).find("td:eq(9)").html(_util.roundEx((d["이글"]*100/per), -1) + "%");
				}else{
					$(this).find("td:eq(8)").html("-");
					$(this).find("td:eq(9)").html("-");
				}
				$(this).find("td:eq(10)").html(d["홀인원"]);
				$(this).find("td:eq(11)").html(_util.roundEx((d["홀인원"]*100/per), -1) + "%");
				$(this).find("td:eq(12)").html(_util.roundEx(total/per, -1));
			});
		}
	}
	
	// 전체스코어 검색
	function clsAllScoreSearch()
	{
		this._HTMLDom = null;
		this._ERRMSG = {
			"_NOVALUE_SDATE": "검색할 시작기간을 설정해 주십시요."
			, "_NOVALUE_EDATE": "검색할 종료기간을 설정해 주십시요."
		}
		this.errMsg = null;
		
		this._init();
	}
	
	clsAllScoreSearch.prototype = {
		_init: function(){
			var $layer = $("div#container dl.score_search");
			this._HTMLDom = {
				"$layer": $layer
			}
			
			var $text = $layer.find("input:text:first").width(80).clone(true);
			
			$layer.find("input:text:first").after($text).after(" ~ ");
			
			$layer.find("img[alt='달력']").hide();
			
			$layer.find("input:text:eq(0)").attr({
				"readonly": "readonly"
			}).datepicker({
				showOn: "both"
				, buttonImage: $layer.find("img[alt='달력']").attr("src")
				, buttonImageOnly: true
			});
			
			$layer.find("input:text:eq(1)").attr({
				"readonly": "readonly"
			}).datepicker({
				showOn: "both"
				, buttonImage: $layer.find("img[alt='달력']").attr("src")
				, buttonImageOnly: true
			});
			
			$layer.find("input:text:last").attr("placeholder", $layer.find("input:text:last").val()).val("");
		}
		, $getLayer: function(){
			return this._HTMLDom["$layer"];
		}
		, getError: function(){
			if(this.errMsg) return this._ERRMSG[this.errMsg];
			else return null;
		}
		, valid: function(){
			var $layer = this._HTMLDom["$layer"];
			var sDate = $layer.find("input:text:eq(0)").val();
			var eDate = $layer.find("input:text:eq(1)").val();
			
			if(sDate && !eDate){
				this.errMsg = "_NOVALUE_EDATE";
					
				return false;
			}else if(!sDate && eDate){
				this.errMsg = "_NOVALUE_SDATE";
					
				return false;
			}
			
			return true;
		}
		, getSValue: function(){
			return this._HTMLDom["$layer"].find("input:text:eq(0)").val();
		}
		, getEValue: function(){
			return this._HTMLDom["$layer"].find("input:text:eq(1)").val();
		}
		, getGolfValue: function(){
			return this._HTMLDom["$layer"].find("input:text:eq(2)").val();
		}
	}
	
	// 전체스코어
	function clsAllScoreList()
	{
		this._HTMLDom = null;
		this.listData = null;
		
		this._init();
	}
	
	clsAllScoreList.prototype = {
		_init: function(){
			var $layer = $("div#container article.list01");
			this._HTMLDom = {
				"$layer": $layer
				, "$element": $layer.find("tbody tr:first").clone(true)
			}
			
			this.setList([]);
		}
		, $getLayer: function(){
			return this._HTMLDom["$layer"];
		}
		, setList: function(thisData){
			this.listData = thisData;
			this.display();
		}
		, display: function(){
			var $layer = this._HTMLDom["$layer"];
			var $element = this._HTMLDom["$element"];
			var thisClass = this;
			
			$layer.find("tbody").empty();
			for(var i=0;i<this.listData.length;i++){
				$layer.find("tbody").append($element.clone(true));
			}
			
			$layer.find("tbody tr").each(function(n){
				var obj = thisClass.listData[n];
				
				$(this).find("td:eq(1)").html(obj["번호"]);
				$(this).find("td:eq(2)").html(obj["날짜"]);
				$(this).find("td:eq(3)").css("cursor", "pointer").html(obj["골프장코스명"]);
				$(this).find("td:eq(4)").html("");
				$(this).find("td:eq(5)").html(obj["홀"]);
				$(this).find("td:eq(6)").html(obj["파"]);
				$(this).find("td:eq(7)").html(obj["스코어"]);
			});
		}
		, spinStart: function(){
			var $layer = this._HTMLDom["$layer"];
			
			$layer.find("tbody").hide();
			if($layer.find("div#tmpSpin").length == 0){
				$layer.append("<div id='tmpSpin' style='position:relative; width:1000px; height:100px;' />	");
			}
			$layer.find("div#tmpSpin").show().spin();
		}
		, spinEnd: function(){
			var $layer = this._HTMLDom["$layer"];
			
			$layer.find("div#tmpSpin").hide().spin(false);
			$layer.find("tbody").show();
		}
		, getKey: function(n){
			return this.listData[n]["스코어코드"];
		}
		, getKeys: function(){
			var $layer = this._HTMLDom["$layer"];
			var thisClass = this;
			var szRet = "";
			
			$layer.find("tbody input:checkbox").each(function(n){
				if($(this).is(":checked")){
					if(szRet) szRet += ",";
					szRet += thisClass.listData[n]["스코어코드"];
				}
			});
			
			return szRet;
		}
		, allCheck: function(){
			var $layer = this._HTMLDom["$layer"];
			
			$layer.find("tbody input:checkbox").attr("CHECKED", Boolean($layer.find("input:checkbox:first").attr("CHECKED")));
		}
	}
	
	
	// 서버통신
	function clsComm()
	{
		// 평균 스코어
		this.avgScore = null;
		// 베스트 스코어
		this.bestScore = null;
		// 최대타수
		this.worstScore = null;
		
		// 스코어 통계
		this.scoreStatList = null;
		this.roundCount = null;
		
		// 전체스코어
		this.allScoreList = null;
		this.allScoreRequest = null;
		this.allScoreListTotalCount = null;
		
		this._init();
	}
	
	clsComm.prototype = {
		_init: function(){
			this.avgScore = {};
			this.bestScore = {};
			this.worstScore = {};
			
			this.scoreStatList = [];
			this.roundCount = 0;
			
			this.allScoreList = [];
			this.allScoreRequest = {};
			this.allScoreListTotalCount = 0;
		}
		// 평균 스코어
		, getAvgScore: function(){
			var thisClass = this;
			
			this.avgScore = {};
			
			//ajax
			var serviceName = "getMyAverageScore";
			document.objGlobal.ajax({
				"sid": "US001"
				, "servicename": serviceName
			}, {
				
			}, function(ret){
				var res = {
					"결과코드": ret["msp"]["contents"]["serviceResult"]
					, "메시지": document.objGlobal.getResultMsg(ret)
				}
				
				var items = ret["msp"]["contents"]["items"];
				if(items) thisClass.avgScore = {
					"스코어": items
				}
				
				document.objControl.finishAvgScore(res);
			});
		}
		, getAvgScoreData: function(){
			return this.avgScore;
		}
		//베스트 스코어
		, getBestScore: function(){
			var thisClass = this;
			
			this.bestScore = {};
			
			//ajax
			var serviceName = "getMyBestScore";
			document.objGlobal.ajax({
				"sid": "US001"
				, "servicename": serviceName
			}, {
				
			}, function(ret){
				var res = {
					"결과코드": ret["msp"]["contents"]["serviceResult"]
					, "메시지": document.objGlobal.getResultMsg(ret)
				}
				
				var items = ret["msp"]["contents"]["items"];
				if(items){
					thisClass.bestScore = {
						"골프장명": items["golfclubName"]
						, "코스명": items["courseInfoName"]
						, "스코어": items["score"]
					}
				}
				
				document.objControl.finishBestScore(res);
			});
		}
		, getBestScoreData: function(){
			return this.bestScore;
		}
		//최대타수
		, getWorstScore: function(){
			var thisClass = this;
			
			this.worstScore = {};
			
			//ajax
			var serviceName = "getMyWorstScore";
			document.objGlobal.ajax({
				"sid": "US001"
				, "servicename": serviceName
			}, {
				
			}, function(ret){
				var res = {
					"결과코드": ret["msp"]["contents"]["serviceResult"]
					, "메시지": document.objGlobal.getResultMsg(ret)
				}
				
				var items = ret["msp"]["contents"]["items"];
				if(items){
					thisClass.worstScore = {
						"골프장명": items["golfclubName"]
						, "코스명": items["courseInfoName"]
						, "스코어": items["score"]
					}
				}
				
				document.objControl.finishWorstScore(res);
			});
		}
		, getWorstScoreData: function(){
			return this.worstScore;
		}
		// 스코어통계
		, getScoreStatList: function(){
			var thisClas = this;
			
			this.scoreStatList = [];
			this.roundCount = 0;
			
			//ajax
			var serviceName = "getMyScoreStats";
			_gf.ajax({
				"sid": "US001"
				, "servicename": serviceName
			}, {
				
			}, function(ret){
				var res = {
					"결과코드": ret["msp"]["contents"]["serviceResult"]
					, "메시지": document.objGlobal.getResultMsg(ret)
				}
				
				var items = ret["msp"]["contents"]["items"];
				if(items){
					var obj = items;
					for(var i=3;i<6;i++){
						thisClas.scoreStatList.push({
							"더블보기": _util.nvl(obj["doubleBogey" + i], 0)
							, "보기": _util.nvl(obj["bogey" + i], 0)
							, "파": _util.nvl(obj["par" + i], 0)
							, "버디": _util.nvl(obj["birdie" + i], 0)
							, "이글": _util.nvl(obj["eagle" + i], 0)
							, "홀인원": _util.nvl(obj["holeInOne" + i], 0)
						});
					}
				}
				
				document.objControl.finishScoreStatList(res);
			});
		}
		, getScoreStatData: function(){
			return this.scoreStatList;
		}
		, getRoundCount: function(){
			return this.roundCount;
		}
		// 전체스코어
		, setAllScoreRequest: function(key, val){
			if(typeof key == "object") this.allScoreRequest = key;
			else this.allScoreRequest[key] = val;
		}
		, getAllScoreList: function(arg){
			var thisClass = this;
			
			this.allScoreList = [];
			this.allScoreListTotalCount = 0;
			
			//ajax
			var serviceName = "getMyScoreAllList";
			var curPage = this.allScoreRequest["페이지"];
			_gf.ajax({
				"sid": "US001"
				, "servicename": serviceName
				, "listcount": this.allScoreRequest["페이지당수"]
				, "currpageno": curPage
			}, {
				"startDt": arg["검색시작일"]
				, "endDt": arg["검색종료일"]
				, "search": arg["검색골프장명"]
			}, function(ret){
				var res = {
					"결과코드": ret["msp"]["contents"]["serviceResult"]
					, "메시지": _gf.getResultMsg(ret)
					, "전체수":  ret["msp"]["contents"]["@totalcount"]
					, "결과값": []
				}
				
				var items = ret["msp"]["contents"]["items"];
				if(items){
					if(!items.length) items = new Array(items);
					
					var no = res["전체수"] - (curPage-1)*thisClass.allScoreRequest["페이지당수"];
					for(var i=0;i<items.length;i++){
						var obj = items[i];
						
						var golfCourseName = "";
						if(_util.nvl(obj["reservSeq"]+"").substrEx(0, 1) == "D"){
							golfCourseName = _util.nvl(obj["golfclubId"]);
						}else{
							golfCourseName = _util.nvl(obj["golfclubName"]) + "/" + _util.nvl(obj["courseInfoName"]);
						}
						
						res["결과값"].push({
							"스코어코드": _util.nvl(obj["reservSeq"])
							, "번호": no-i
							, "날짜": _util.nvl(obj["regDate"])
							, "골프장코스명": golfCourseName
							, "홀": _util.nvl(obj["holeCnt"])
							, "파": _util.nvl(obj["par"])
							, "스코어": _util.nvl(obj["score"])
						});
					}
				}
				
				document.objControl.finishAllScoreList(res);
			});
		}
		, getAllScoreData: function(){
			return this.allScoreList;
		}
		, getAllScoreTotalCount: function(){
			return this.allScoreListTotalCount;
		}
		// 스코어카드 삭제
		, scoreCardDelete: function(arg){
			var thisClass = this;
			
			//ajax
			var serviceName = "deleteMyScoreCard";
			var options = {
				"reservSeq": arg["스코어카드코드"]
			}
			_gf.ajax({
				"sid": "US001"
				, "servicename": serviceName
			}, options, function(ret){
				var res = {
					"결과코드": ret["msp"]["contents"]["serviceResult"]
					, "메시지": _gf.getResultMsg(ret)
				}
				
				document.objControl.finishScoreCardDelete(res);
			});
		}
	}
	
	// 컨트롤
	function clsControl()
	{
		this.objComm = null;
		this.objAvgScore = null;
		this.objBestScore = null;
		this.objWorstScore = null;
		this.objScoreStatList = null;
		this.objAllScoreSearch = null;
		this.objAllScoreList = null;
		this.objAllScoreListPage = null;
	}
	
	clsControl.prototype = {
		_init: function(){
			this.objComm = new clsComm();
			this.objAvgScore = new clsAvgScore();
			this.objBestScore = new clsBestScore();
			this.objWorstScore = new clsWorstScore();
			this.objScoreStatList = new clsScoreStatList();
			this.objAllScoreSearch = new clsAllScoreSearch();
			this.objAllScoreList = new clsAllScoreList();
			
			this._preload();
			this._bind();
			
			this.objAllScoreSearch.$getLayer().find("img[alt='검색']").trigger("click");
		}
		, _preload: function(){
			var thisClass = this;
			
			_gf.spinStart();
			$.ajax({
				url: _ROOT + "/js/mypage_common.js"
				, dataType: "script"
				, async: false
				, success: function(){
					
				}
				, error: function(){
					alert("error");
				}
			});
			
			var $pageDiv = $("ul.pagenum_area").wrap("<div />").parent("div").empty();
			this.objAllScoreListPage = new _gf.makePaging($pageDiv, 10, 10);
			this.objComm.setAllScoreRequest("페이지당수", this.objAllScoreListPage.getCountPerPage());
			
			
			_util.executeThread(function(){
				return (_gf.getMyInfoData());
			}, function(){
				_gf.spinEnd();
				thisClass._start();
			});
		}
		, _bind: function(){
			var thisClass = this;
			
			// 검색
			this.objAllScoreSearch.$getLayer().on("click", "img[alt='검색']", function(){
				thisClass.objComm.setAllScoreRequest("페이지", 1);
				
				thisClass.allScoreList();
			});
			
			// 페이지이동
			$(this.objBookingPage).bind("evtPageClick", function(){
				var thisPage = this.getPage();
				
				thisClass.objComm.setAllScoreRequest("페이지", thisPage);
				
				thisClass.allScoreList();
			});
			
			// 스코어 등록
			$("div#container").on("click", "img[alt='스코어 등록']", function(){
				document.location.href = _ROOT + "/mypage/my_score_write.html";
			});
			
			// 스코어 클릭
			this.objAllScoreList.$getLayer().on("click", "tbody tr td:nth-child(4)", function(){
				var n = thisClass.objAllScoreList.$getLayer().find("tbody tr td:nth-child(4)").index($(this));
				var k = thisClass.objAllScoreList.getKey(n);
				
				document.location.href = _ROOT + "/mypage/my_score_rd.html?q_seq=" + k;
			});
			
			// 스코어 카드 전체 선택
			this.objAllScoreList.$getLayer().on("click", "input:checkbox:first", function(){
				thisClass.objAllScoreList.allCheck();
			});
			
			// 스코어 카드 삭제
			$("div#container").on("click", "img[alt='삭제']", function(){
				var s = thisClass.objAllScoreList.getKeys();
				
				if(!s){
					alert("삭제할 스코어 카드를 선택해 주십시요.");
					return;
				}
				
				if(!confirm("삭제하시겠습니까?")) return;
				
				thisClass.objComm.scoreCardDelete({
					"스코어카드코드": s
				});
			});
		}
		, _start: function(){
			// 평균스코어
			this.objComm.getAvgScore();
			// 베스트스코어
			this.objComm.getBestScore();
			// 최대타수
			this.objComm.getWorstScore();
			// 스코어통계
			this.objComm.getScoreStatList();
			// 전체스코어
			this.objAllScoreListPage.setPage(1);
			this.allScoreList();
		}
		// 전체스코어 검색
		, allScoreList: function(){
			if(!this.objAllScoreSearch.valid()){
				alert(this.objAllScoreSearch.getError());
				return;
			}
			
			this.objAllScoreList.spinStart();
			this.objComm.setAllScoreRequest("페이지", this.objAllScoreListPage.getPage());
			this.objComm.getAllScoreList({
				"검색시작일": this.objAllScoreSearch.getSValue()
				, "검색종료일": this.objAllScoreSearch.getEValue()
				, "검색골프장명": this.objAllScoreSearch.getGolfValue()
			});
		}
		// 평균 스코어 완료
		, finishAvgScore: function(ret){
			if(ret["메시지"]) alert(ret["메시지"]);
			if(ret["결과코드"] != "00000") return;
			
			var thisData = this.objComm.getAvgScoreData();
			
			this.objAvgScore.setInfo(thisData);
		}
		// 베스트 스코어 완료
		, finishBestScore: function(ret){
			if(ret["메시지"]) alert(ret["메시지"]);
			if(ret["결과코드"] != "00000") return;
			
			var thisData = this.objComm.getBestScoreData();
			
			this.objBestScore.setInfo(thisData);
		}
		// 최대타수 완료
		, finishWorstScore: function(ret){
			if(ret["메시지"]) alert(ret["메시지"]);
			if(ret["결과코드"] != "00000") return;
			
			var thisData = this.objComm.getWorstScoreData();
			
			this.objWorstScore.setInfo(thisData);
		}
		// 스코어통계 완료
		, finishScoreStatList: function(ret){
			if(ret["메시지"]) alert(ret["메시지"]);
			if(ret["결과코드"] != "00000") return;
			
			var thisData = this.objComm.getScoreStatData();
			
			this.objScoreStatList.setList(thisData);
		}
		// 전체스코어 완료
		, finishAllScoreList: function(ret){
			if(ret["메시지"]) alert(ret["메시지"]);
			if(ret["결과코드"] != "00000") return;
			
			this.objAllScoreList.spinEnd();
			
			var thisData = ret["결과값"];
			var totalCount = ret["전체수"];
			
			this.objScoreStatList.setRoundCount(totalCount);
			
			this.objAllScoreList.setList(thisData);
			this.objAllScoreListPage.setTotalCount(totalCount);
			this.objAllScoreListPage.display();
		}
		// 스코어카드 삭제 완료
		, finishScoreCardDelete: function(ret){
			if(ret["메시지"]) alert(ret["메시지"]);
			if(ret["결과코드"] != "00000") return;
			
			// 전체스코어
			this.objAllScoreListPage.setPage(1);
			this.allScoreList();
		}
	}
	
	document.objControl = new clsControl();
	document.objControl._init();
});
